package it.rossignoli.enrico.app.Tesi;


import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;


//Activity list che mi servira per gestire il training e l invio dei gesti sulla sib

//integro nella classe il servizio gesti

import de.dfki.ccaal.gestures.IGestureRecognitionListener;
import de.dfki.ccaal.gestures.IGestureRecognitionService;
import de.dfki.ccaal.gestures.classifier.Distribution;


public class ListT extends Activity 
{
	
	//variabili supporto per connessione alla sib
	
	Intent serviceIntent;
	private ResponseReceiverTraining receiver;
	private IntentFilter filter;
	
	//Classe di appoggio per il servizio gesti
	IGestureRecognitionService recognitionService;
	//Stringa contenente i tipi di gesto che si possono riconoscere
	ArrayList<String> values =new ArrayList<String>(); //{ "MoveUp","MoveDown","MoveLeft","MoveRight"};
	String Del;
	ListView lv;
	int count=0;


	//metodi necessari al servizio gesti
	//creazione della connessione
	private final ServiceConnection serviceConnection = new ServiceConnection() 
	{

		
		public void onServiceConnected(ComponentName className, IBinder service) 
		{
			recognitionService = IGestureRecognitionService.Stub.asInterface(service);
			try 
			{
				//Faccio partire in modalita riconoscimento e attivo pure il recorder
				//recognitionService.startClassificationMode("default");
				//Registro il listener in maniera tale da poter recepire le informazioni inviate dal servizio sfruttando i metodi dell interfaccia listener
				//Posso quindi usare i metodi implementati nello stub di questa activity

				recognitionService.registerListener(IGestureRecognitionListener.Stub.asInterface(gestureListenerStub));
				
				SharedPreferences prefs= getSharedPreferences("PREFERENCES_UTENTE", Context.MODE_PRIVATE);
				String Set=prefs.getString("Selected", "default").toString();
				List<String> Item= recognitionService.getGestureList(Set);
//				MyArrayAdapter adapter = new MyArrayAdapter(ListT.this,values, Item);
//				ListView lv =(ListView) findViewById(R.id.listViewtrain); 
//				lv.setAdapter(adapter);
			} 
			catch (RemoteException e1) 
			{
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}

		
		public void onServiceDisconnected(ComponentName className) 
		{
			recognitionService = null;
		}
	};

	protected boolean imparato;

	//implementazione dei metodi di ritorno dello stub
	IBinder gestureListenerStub = new IGestureRecognitionListener.Stub() 
	{

		
		public void onGestureLearned(final String gestureName) throws RemoteException 
		{
			
			System.err.println("Gesture"+gestureName +" learned");
//			count++;
//			imparato=false;
//			if(count!=3)
//			{
//				runOnUiThread(new Runnable() 
//				{
//					
//					public void run() 
//					{
//						Toast.makeText(ListT.this, gestureName+":"+count, Toast.LENGTH_LONG).show();
//						
//					}
//				});
//			}
//			else
//			{
//				imparato=true;
//				runOnUiThread(new Runnable() 
//				{
//					
//					public void run() 
//					{
//						Toast.makeText(ListT.this, String.format("%s imparato",gestureName), Toast.LENGTH_LONG).show();
//						
//					}
//				});
//				
//				refreshList();
//			}

		}

		
		public void onTrainingSetDeleted(String trainingSet) throws RemoteException 
		{
//			Toast.makeText(ProvaTrainingActivity.this, String.format("Training set %s deleted", trainingSet), Toast.LENGTH_SHORT).show();
//			System.err.println(String.format("Training set %s deleted", trainingSet));
		}

		
		public void onGestureRecognized(final Distribution distribution) throws RemoteException 
		{
			runOnUiThread(new Runnable() 
			{
				
				public void run() 
				{
//					Toast.makeText(ProvaTrainingActivity.this, String.format("%s: %f", distribution.getBestMatch(), distribution.getBestDistance()), Toast.LENGTH_LONG).show();
//					System.err.println(String.format("%s: %f", distribution.getBestMatch(), distribution.getBestDistance()));
				}
			});
		}
	};
	
	
	public void onCreate(Bundle icicle) 
	{
		super.onCreate(icicle);
		
		setContentView(R.layout.listt);
		
		ListView lv =(ListView) findViewById(R.id.listViewtrain); 
		
		Button OkTrain = (Button)findViewById(R.id.OkTrain);
		Button NewIP = (Button)findViewById(R.id.BNewIP);
		
		final EditText TextNewIP = (EditText)findViewById(R.id.NewIP);
		lv.setTextFilterEnabled(true);
		registerForContextMenu(lv);

		OkTrain.setOnClickListener(new OnClickListener()
		{
			
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				Intent i=new Intent(ListT.this, RFIDActivity.class);
				startActivity(i);
				finish();
			}
		});
		
		NewIP.setOnClickListener(new OnClickListener() 
		{
			
			public void onClick(View v) 
			{
				// TODO Auto-generated method stub
				SharedPreferences prefs= getSharedPreferences("PREFERENCES_UTENTE", Context.MODE_PRIVATE);
				String Set=prefs.getString("Selected", "default").toString();
				List<String> Item;
//				try 
//				{
//					Item = recognitionService.getGestureList(Set);
					values.add(TextNewIP.getText().toString());
					
			    	serviceIntent = new Intent(ListT.this, SibIntentService.class);
			    	serviceIntent.putExtra(SibIntentService.PARAM_IN_TYPE,SibIntentService.typeIntent.INSERT);
			    	serviceIntent.putExtra("NewIPType",TextNewIP.getText().toString() );
			    	startService(serviceIntent);
//					String[] gesti= new String[values.size()];
//					
//					for(int i=0; i<values.size(); i++)
//					{
//						gesti[i]=values.get(i).toString();
//					}
//					
//					MyArrayAdapter adapter = new MyArrayAdapter(ListT.this,gesti, Item);
//					ListView lv =(ListView) findViewById(R.id.listViewtrain); 
//					lv.setAdapter(adapter);
//				} 
//				catch (RemoteException e) 
//				{
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
			}
		});
		
		lv.setOnItemClickListener(new OnItemClickListener() 
		{

			public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) 
			{
				// TODO Auto-generated method stub
				List<String> Item;
				
				//gestire il training 
				
				if (recognitionService != null) {
					try {
						if (true) 
						{
							
							SharedPreferences prefs= getSharedPreferences("PREFERENCES_UTENTE", Context.MODE_PRIVATE);
							String Set=prefs.getString("Selected", "default").toString();
							Item = recognitionService.getGestureList(Set);
							//recognitionService.startLearnMode(Set,Item.get(position));
							Intent Train = new Intent(ListT.this, ExecTrain.class);
							Train.putExtra("Set", Set);
							Train.putExtra("Gesto", values.get(position));
							startActivity(Train);
						} 
						else 
						{
							//recognitionService.stopLearnMode();
						}
					} catch (RemoteException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			}
		});
		showDialog(0);
		
        filter = new IntentFilter(ResponseReceiverTraining.ACTION_RESP_TRAIN);
    	filter.addCategory(Intent.CATEGORY_DEFAULT);
    	filter.addAction(ResponseReceiverTraining.ACTION_RESP_TRAIN_REFRESH);
    	receiver = new ResponseReceiverTraining();

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) 
	{
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		menu.setHeaderTitle("Cancella Gesto Insegnato");
		String[] menuItems = { "Delete" };
		
		SharedPreferences prefs= getSharedPreferences("PREFERENCES_UTENTE", Context.MODE_PRIVATE);
		String Set=prefs.getString("Selected", "default").toString();
		
			
		Del=values.get(info.position);

	
		for (int i = 0; i < menuItems.length; i++) {
			menu.add(Menu.NONE, i, i, menuItems[i]);
		}

		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) 
	{
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

		if (item.getItemId() == 0) {
			try 
			{
				
				SharedPreferences prefs= getSharedPreferences("PREFERENCES_UTENTE", Context.MODE_PRIVATE);
				String Set=prefs.getString("Selected", "default").toString();
				recognitionService.deleteGesture(Set, Del);
				List<String> items = recognitionService.getGestureList(Set);
				
				String[] gesti= new String[values.size()];
				
				for(int i=0; i<values.size(); i++)
				{
					gesti[i]=values.get(i).toString();
				}
				
				MyArrayAdapter adapter = new MyArrayAdapter(ListT.this,gesti, items);
				ListView lv =(ListView) findViewById(R.id.listViewtrain); 
				lv.setAdapter(adapter);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return true;

	}
	
//	protected void refreshList() 
//	{
//		// TODO Auto-generated method stub
//		List<String> Item;
//		
//		try {
//			SharedPreferences prefs= getSharedPreferences("PREFERENCES_UTENTE", Context.MODE_PRIVATE);
//			String Set=prefs.getString("Selected", "default").toString();
//			Item = recognitionService.getGestureList(Set);
//			MyArrayAdapter adapter = new MyArrayAdapter(ListT.this,values, Item);
//			ListView lv =(ListView) findViewById(R.id.listViewtrain); 
//			lv.setAdapter(adapter);
//			if(count==3)
//			{
//				count=0;
//				recognitionService.stopLearnMode();
//			}
//		} catch (RemoteException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//
//	}

//	protected void onListItemClick(ListView l, View v, int position, long id) 
//	{
//		List<String> Item;
//		
//		//gestire il training 
//		
//		if (recognitionService != null) {
//			try {
//				if (true) 
//				{
//					
//					SharedPreferences prefs= getSharedPreferences("PREFERENCES_UTENTE", Context.MODE_PRIVATE);
//					String Set=prefs.getString("Selected", "default").toString();
//					Item = recognitionService.getGestureList(Set);
//					//recognitionService.startLearnMode(Set,Item.get(position));
//					Intent Train = new Intent(ListT.this, ExecTrain.class);
//					Train.putExtra("Set", Set);
//					Train.putExtra("Gesto", Item.get(position));
//					startActivity(Train);
//				} 
//				else 
//				{
//					recognitionService.stopLearnMode();
//				}
//			} catch (RemoteException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
//	}
	
		
	protected void onRestart() 
	{
		super.onRestart();
		Log.i("ActivityDemo", "Richiamato onRestart()");
	}
	
	@Override
	protected void onStart() 
	{
		super.onStart();
		Log.i("ActivityDemo", "Richiamato onStart()");
	}
	
	@Override
	protected void onResume() 
	{
		//creo la connessione vera al servizio gesti
		Log.i("ActivityDemo", "Richiamato onResume()");
		Intent bindIntent = new Intent("de.dfki.ccaal.gestures.GESTURE_RECOGNIZER");
		bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
		
			//List<String> Item= recognitionService.getGestureList(Set);
		//lego il receveir al main thread principale che viene attivato ogni qualvolta si riceve un brodcast che match con il filtro
		registerReceiver(receiver, filter);

		//eseguo una lettura sulla sib per vedere le interaction primitve che sono presenti
    	//Richiamo il sibintent service
    	serviceIntent = new Intent(this, SibIntentService.class);
    	serviceIntent.putExtra(SibIntentService.PARAM_IN_TYPE,SibIntentService.typeIntent.REFRESH);
    	startService(serviceIntent);
 
		
		super.onResume();

	}
	
	@Override
	protected void onPause() 
	{
		
		Log.i("ActivityDemo", "Richiamato onPause()");
		//Disconnetto il listener ai metodi dello stub
		try 
		{
			recognitionService.unregisterListener(IGestureRecognitionListener.Stub.asInterface(gestureListenerStub));
		} catch (RemoteException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		recognitionService = null;
		//mi disconetto dal servizio
		unbindService(serviceConnection);
		
		unregisterReceiver(receiver);
		super.onPause();
	}
	
	@Override
	protected void onStop() 
	{
		super.onStop();
		Log.i("ActivityDemo", "Richiamato onStop()");
	}
	
	@Override
	protected void onDestroy() 
	{
		super.onDestroy();
		Log.i("ActivityDemo", "Richiamato onDestroy()");
	}
	
	protected Dialog onCreateDialog(int id) 
	{
	    Dialog dialog;
	    
	    dialog= createInfoDialog();
	
	    return dialog;
	}
    
    private Dialog createInfoDialog() 
    {
    	// Otteniamo il riferimento al Builder
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Impostiamo il titolo, il messaggio ed una icona in chaining
		builder.setTitle(R.string.alertDialogInfo_label);
		builder.setIcon(R.drawable.ic_launcher);
		builder.setCancelable(false);
		builder.setMessage(R.string.alertDialogInfo_message);
		// Impostiamo il pulsante di Yes con il relativo listener
		builder.setPositiveButton(R.string.alertDialogInfo_positiveLabel,
			new DialogInterface.OnClickListener() 
			{
	
				
				public void onClick(DialogInterface dialog, int id) 
				{
					dialog.dismiss();
				}
	
			});
		// Ritorniamo l'Alert creato
		return builder.create();
    }
    
    //Classe accessoria che riceve i messaggi provenienti dalla sib
    public class ResponseReceiverTraining extends BroadcastReceiver 
    {
    	

        public static final String ACTION_RESP_TRAIN = "MESSAGE_PROCESSED";
        public static final String ACTION_RESP_TRAIN_REFRESH = "MESSAGE_PROCESSED_REFRESH";
        String IPTypeString;
        @Override
        public void onReceive(Context context, Intent intent) 
        {
        	
        	if(intent.getAction().equals(ACTION_RESP_TRAIN))
        	{
                // Update UI, new "message" processed by SimpleIntentService
                boolean r = intent.getBooleanExtra(SibIntentService.PARAM_OUT_RESULT,false);
                if(r)
                {
     				IPTypeString=intent.getStringExtra("IPType");
     				
     				String[] temp=IPTypeString.split(",");
     				//values.clear();
     				
     				for(int i=0; i<temp.length; i++)
     				{
     					//controllo che i dati ndella sib non vengano riaggiunti alla lista dei gesti
     					if(values.contains(temp[i]))
     					{
     						
     					}
     					else
     					{
     						values.add(temp[i]);
     					}
     					
     				}
     				
     				SharedPreferences prefs= getSharedPreferences("PREFERENCES_UTENTE", Context.MODE_PRIVATE);
     				String Set=prefs.getString("Selected", "default").toString();
     				List<String> Item;
     				String[] gesti = new String[values.size()];
     				for(int i=0; i<values.size(); i++)
     				{
     					gesti[i]=values.get(i).toString();
     				}
     				try 
     				{
     					Item = recognitionService.getGestureList(Set);
     					MyArrayAdapter adapter = new MyArrayAdapter(ListT.this, gesti, Item);
     					ListView lv =(ListView) findViewById(R.id.listViewtrain); 
     					lv.setAdapter(adapter);
     				} 
     				catch (RemoteException e) 
     				{
     					// TODO Auto-generated catch block
     					e.printStackTrace();
     				}
                }
                else
                {
             	   
                }
        	}
        	else if(intent.getAction().equals(ACTION_RESP_TRAIN_REFRESH))
        	{
            	serviceIntent = new Intent(ListT.this, SibIntentService.class);
            	serviceIntent.putExtra(SibIntentService.PARAM_IN_TYPE,SibIntentService.typeIntent.REFRESH);
            	startService(serviceIntent);
        	}
        	
        	

           
        }
        
    }
    
    
    
	
}